import json

from django.http import JsonResponse, HttpResponseNotFound
from rest_framework import status
from django.views import View
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from rest_framework.generics import ListAPIView
from rest_framework.views import APIView
from rest_framework.generics import GenericAPIView, ListCreateAPIView, RetrieveUpdateDestroyAPIView
from rest_framework.mixins import ListModelMixin, CreateModelMixin, UpdateModelMixin, DestroyModelMixin, \
    RetrieveModelMixin
from rest_framework.viewsets import ViewSet, GenericViewSet, ModelViewSet, ReadOnlyModelViewSet

from books.models import BookInfo, HeroInfo
from books.serializers import BookInfoSerializer


# 定义 ModelViewSet
# class BookInfoViewSet(ModelViewSet):
#     queryset = BookInfo.objects.all()
#     serializer_class = BookInfoSerializer


# 1.符合 restful 风格 功能实现

# 1.符合 restful 风格 功能实现
class BooksView(ReadOnlyModelViewSet):
    queryset = BookInfo.objects.all()
    serializer_class = BookInfoSerializer








# 英雄的CRUD 操作
class HerosView(View):
    def get(self, request):
        # 如果有搜索功能 是要传递 keyword 查询参数
        keyword = request.GET.get('keyword')
        queryset = HeroInfo.objects
        if keyword:
            heros = queryset.filter(hname__contains=keyword)
        else:
            # 没有 的话 默认 返回所有图书
            heros = queryset.all()

        # 构建前端 需要的 [{}]
        heros_list = []
        for hero in heros:
            heros_list.append({
                'id': hero.id,
                'hname': hero.hname,
                'hgender': hero.hgender,
                'hcomment': hero.hcomment,
                'hbook': hero.hbook.btitle,
            })

        return JsonResponse(heros_list, safe=False)

    # 注意:前端传入的 hbook_id 只有int类型, 前端没有Python对象
    def post(self, request):
        # 1.接收参数
        json_dict = json.loads(request.body.decode())
        # 2.校验参数--省略
        # 3.创建新数据
        hero = HeroInfo.objects.create(**json_dict)
        # 4.构建前端需要的格式 {}
        hero_dict = {
            'id': hero.id,
            'hname': hero.hname,
            'hgender': hero.hgender,
            'hcomment': hero.hcomment,
            'hbook': hero.hbook.btitle,
        }
        # 5.返回响应对象
        return JsonResponse(hero_dict, status=201)


class HeroView(View):
    def get(self, request, pk):
        # 1.根据主键id查询 英雄
        try:
            hero = HeroInfo.objects.get(pk=pk)
        except HeroInfo.DoesNotExist:
            return HttpResponseNotFound('图书不存在!')

        # 2.构建前端的数据格式
        hero_dict = {
            'id': hero.id,
            'hname': hero.hname,
            'hgender': hero.hgender,
            'hcomment': hero.hcomment,
            'hbook': hero.hbook.btitle,
        }
        # 3.返回结果
        return JsonResponse(hero_dict)

    def put(self, request, pk):

        # 1.接收参数
        json_dict = json.loads(request.body.decode())

        # 2.校验--省略

        # 3.根据主键id查询 英雄
        try:
            hero = HeroInfo.objects.get(pk=pk)
        except HeroInfo.DoesNotExist:
            return HttpResponseNotFound('图书不存在!')

        # 4.修改
        hero.hname = json_dict.get('hname')
        hero.hgender = json_dict.get('hgender')
        # 模型类的隐藏属性
        hero.hbook_id = json_dict.get('hbook_id')
        hero.save()

        # 5.构建前端的数据格式
        hero_dict = {
            'id': hero.id,
            'hname': hero.hname,
            'hgender': hero.hgender,
            'hcomment': hero.hcomment,
            'hbook': hero.hbook.btitle,
        }
        # 3.返回结果
        return JsonResponse(hero_dict)

    def delete(self, request, pk):

        # 1.获取需要删除的数据
        try:
            hero = HeroInfo.objects.get(pk=pk)
        except HeroInfo.DoesNotExist:
            return HttpResponseNotFound('图书不存在!')

        # 2.删除
        hero.delete()

        # 3.返回结果
        return JsonResponse({}, status=204)
